class Solution {
public:
    int longestArithSeqLength(vector<int>& nums) {
        int n = nums.size();
        vector<vector<int>> dp(n, vector<int>(n, 2));
        unordered_map<int, int> hash;

        hash[nums[0]] = 0;

        int ans = 0;
        int maxl = 2;
        for (int j = 1; j < n - 1; ++j)
        {
            for (int i = j + 1; i < n; ++i)
            {
                ans = nums[j] - (nums[i] - nums[j]);
                if (hash.count(ans) != 0 && hash[ans] < j)
                    dp[j][i] = dp[hash[ans]][j] + 1;
                maxl = max(maxl, dp[j][i]);
            }
            hash[nums[j]] = j;
        }
        return maxl;
    }
};